import sys
import json
from pymongo import MongoClient
import pymongo
from decimal import Decimal
city=sys.argv[1]
db_name=sys.argv[2]
client=MongoClient("101.200.122.53",3719)
db=client['admin']
db.authenticate('root', 'zhuge1116')
db=client[db_name]
borough_price_file="%s/borough" % city
def default(obj):
    if isinstance(obj, Decimal):
        return str(obj)
    raise TypeError
newitem={}
print 'haha'
with open(borough_price_file, 'w') as f:
    print 'count=',db['borough'].find().count()
    cnt=0
    for item in db['borough'].find(no_cursor_timeout=True):
        cnt=cnt+1
        print 'cnt=',cnt
    #boroughList=list(db['borough'].find())
    #for item in boroughList:
        print 'in for'
        try:
            for name in item['borough_byname']:
                print name
                newitem['borough_name']=name
                newitem['id']=item['_id']
                try:
                    print 'in try'
                    newitem['cityarea_id']=item['cityarea']['cityarea']['cityarea_id']
                    newitem['cityarea2_id']=item['cityarea']['cityarea2'][0]['cityarea2_id']
                except:
                    print 'in except'
                    newitem['borough_name']=name
                    newitem['id']=item['_id']
                    newitem['cityarea_id']= '0'
                    newitem['cityarea2_id']= '0'
                if item.get('traffic') and item.get('traffic').get('subway'):
                    newitem['subway']= '1'
                else:
                    newitem['subway']= '0'
                print 'before write'
                print 'newitem=', newitem
                f.write(json.dumps(newitem,default=default))
                f.write("\n")
                print 'after write'
        except Exception as e:
            print 'out except'
            print e
            continue
print 'done'
f.close()
print 'done1'
